//
//  ScoreRequest.m
//  PlayBall
//
//  Created by Jdd‘s macbook on 13-9-29.
//
//

#import "JddScoreHTTPRequest.h"
#import "JddParameterBuilder.h"
#import "JSONKit.h"
@implementation JddScoreHTTPRequest
SHARED_INSTANCE_DEFINE(JddScoreHTTPRequest)
-(void)start
{
    NSString *str = [JddParameterBuilder buildScoreParameterWithParameterLastTime:self.lastTime AndLotterId:self.lotterId];
    NSData *bodyData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url = SCORE_URL;
    NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:TIMEOUT_INTERVAL];
	
    [request setHTTPMethod:@"POST"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:bodyData];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Accept"];
    if (topAppsConnection) 
        [topAppsConnection cancel];
    topAppsConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (topAppsConnection)
        self.topAppsData = [NSMutableData data];
}

#pragma mark -
#pragma mark Memory management

- (void)cancel:(NSURLConnection *)connection {
    [connection cancel];
    self.topAppsData = nil;
}

#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSInteger status = [(NSHTTPURLResponse *)response statusCode];
    if (status != 200)
        [self cancel:connection];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.topAppsData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self cancel:connection];
     [self.delegate performSelector:@selector(ScoreHTTPRequestResult:) withObject:nil];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *topAppsString = [[NSString alloc] initWithData:self.topAppsData encoding:NSUTF8StringEncoding];
    self.topAppsData = nil;
    [self.delegate performSelector:@selector(ScoreHTTPRequestResult:) withObject:topAppsString];
}

@end
